// 发布评价
import React, { useState } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Input, Button, Image, } from '@tarojs/components';
import { Rate, Uploader, TextArea, Switch, Toast } from '@nutui/nutui-react-taro'
import { AddComment } from '../../types/comment'
import { getToken, setToken } from '../../utils/cookies'
// import 'taro-vant-ui/dist/style/index.css';
import { postComment } from '../../api'
import { showLoading, hideLoading } from "@tarojs/taro";
import './index.scss';
import { useRouter } from "@tarojs/taro";
const Index: React.FC = () => {
  const router = useRouter();
  const { db_man, order_id, product_id } = router.params;
  if (db_man) {
    setToken('db_man', db_man)
  }
  const [addComment, setAddComment] = useState<AddComment>({
    product_id: Number(product_id) || 0,                // 商品ID，标识被评论的商品
    order_id: Number(order_id) || 0,              // 订单ID，关联用户购买记录
    review_text: '',              // 评论内容，用户对商品的具体评价文本
    quality_score: 0,             // 质量评分（1-5分）
    service_score: 0,             // 服务评分（1-5分）
    delivery_score: 0,              // 物流评分（1-5分）
    overall_score: 0,             // 综合评分（1-5分）
    review_images: [],                // 评论图片列表，存储图片URL数组
    video_url: '',               // 视频评价链接（可选）
    is_anonymous: 0,              // 是否匿名评价：0-否，1-是
  })
  const onChange = (e, type: string) => {
    setAddComment({
      ...addComment,
      [type]: e
    })
  }


  const onSubmitReview = async () => {
    showLoading({
      title: '加载中...',
      mask: true // 防止触摸穿透
    })
    if (!addComment.review_text) {
      hideLoading()
      Toast.show('test', {
        title: '请输入评论内容',
        content: '请输入评论内容',
        type: 'fail',
        duration: 2,
        position: 'center',
        // icon: <Jd />,
        lockScroll: true,
        onClose: () => {
          console.log('close')
        },
      })
      return
    }
    try {
      let { data, success } = await postComment(addComment)
      if (success) {
        Toast.show('test', {
          title: '评价提交成功',
          content: '评价提交成功',
          type: 'fail',
          duration: 2,
          position: 'center',
          // icon: <Jd />,
          lockScroll: true,
          onClose: () => {
            console.log('close')
          },
        })
        hanldleData()
      }
    } catch (e) {

    }
    finally {
      hideLoading()
    }

    // 这里可以添加提交评价的逻辑

    // Taro.showToast({
    //   title: '评价提交成功',
    //   icon: 'success'
    // });
  };
  console.log(addComment)
  const hanldleData = () => {
    // 在网页中发送消息（需要配合上面的 injectedJavaScript）

    window?.ReactNativeWebView.postMessage(JSON.stringify({
      action: 'BUTTON_CLICKED',
      data: { item: {}, select: true }
    }));
  }
  return (
    <View className="review-page">
      <Toast id="test" />
      <View className="score-section">
        <View className="score-item">
          <Text>描述相符</Text>
          <Rate value={addComment.quality_score} onChange={(e) => {
            onChange(e, 'quality_score')
          }} />
        </View>
        <View className="score-item">
          <Text>物流服务</Text>
          <Rate value={addComment.delivery_score} onChange={(e) => {
            onChange(e, 'delivery_score')
          }} />
        </View>
        <View className="score-item">
          <Text>服务态度</Text>
          <Rate value={addComment.service_score} onChange={(e) => {
            onChange(e, 'service_score')
          }} />
        </View>
      </View>
      <View className="content-section">
        <Text>评价内容</Text>
        <TextArea
          placeholder="请输入评价内容"
          value={addComment.review_text}
          onChange={(e) => {

            onChange(e, 'review_text')
          }}
          maxLength={200}
          showCount
          rows={8}
        />
      </View>
      <View className="upload-section">
        <Text>发布图片和视频</Text>
        <Uploader
          url={'https://dbyxs.xyz/img'} headers={{
            // cookie: getToken(),
            Authorization: 'Bearer ' + getToken(),
          }}
          maxCount={4}
          onSuccess={(e) => {
            let { responseText } = e
            let { prdUrl } = JSON.parse(responseText).data
            let handleData = addComment.review_images.concat(prdUrl)
            setAddComment({
              ...addComment,
              review_images: handleData
            })
            // console.log(JSON.parse(responseText))
          }}
          onDelete={(e, index) => {

          }}
          multiple
        />
      </View>
      <View className="option-section">
        <View className="option-item">
          <Text>匿名评价</Text>
          <Switch checked={addComment.is_anonymous ? true : false} onChange={(e) => {
            onChange(e ? 1 : 0, 'is_anonymous')
          }} />
        </View>
      </View>
      <View className="submit-section">
        <Button onClick={onSubmitReview}>公开发布</Button>
      </View>
    </View>
  );
};

export default Index;
